package com.leyou.user.serivce.impl;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.serivce.UserService;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "user:verify:";

    /**
     * 校验数据是否可用，type=1校验用户名，type=2校验手机号
     *
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean checkUser(String data, Integer type) {
        User record = new User();
        if (type == 1) {
            //检验用户名
            record.setUsername(data);
        } else if (type == 2) {
            //校验手机号
            record.setPhone(data);
        } else {
            return null;
        }
        return userMapper.selectCount(record) == 0;
    }

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public void sendVerifyCode(String phone) {

        if (StringUtils.isBlank(phone)) {
            return;
        }

        //生成验证码
        String code = NumberUtils.generateCode(6);

        //发送消息到rabbitMQ
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend("leyou.sms.exchange", "verifycode.sms", msg);

        //把验证码保存到redis  设置五分钟过期
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 注册
     * @param user
     * @param code
     */
    @Transactional
    @Override
    public void register(User user, String code) {

        //查询redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        //校验验证码
        if (!StringUtils.equals(code, redisCode)) {
            return;
        }

        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //加盐加密
        String password = CodecUtils.md5Hex(user.getPassword(), salt);
        user.setPassword(password);

        //新增用户
        user.setId(null);   //防止注入
        user.setCreated(new Date());
        userMapper.insertSelective(user);

        //注册成功后，立即删除redis验证码
        redisTemplate.delete(KEY_PREFIX + user.getPhone());
    }

    @Override
    public User queryUser(String username, String password) {
        //通过用户名查该用户的盐
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        //判断user是否为空
        if(user == null){
            return null;
        }
        //获取盐，对用户输入的密码加盐加密
        password = CodecUtils.md5Hex(password, user.getSalt());
        //和数据库中的密码比较
        if(StringUtils.equals(password, user.getPassword())){
            return user;
        }
        return null;
    }
}
